package com.chs.recoginition.core.handler;
import com.chs.recoginition.netty.SessionGroup;
import com.chs.recoginition.netty.SocketSession;
import com.chs.recoginition.pojo.WebSocketMessageResult;
import com.chs.recoginition.repository.WebSocketMessageRepository;
import com.chs.recoginition.service.IUserinfoService;
import com.chs.recoginition.vo.respVo.UserRespVo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.springframework.context.ApplicationContext;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * @Author CHS
 * @Date 2022/8/30 14:02
 * @Version 1.0
 **/

public class WebSocketTextHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private static ApplicationContext applicationContext;
    public static void setApplicationContext(ApplicationContext applicationContext) {
        WebSocketTextHandler.applicationContext = applicationContext;
    }
    IUserinfoService iUserinfoService = applicationContext.getBean(IUserinfoService.class);
    WebSocketMessageRepository webSocketMessageRepository = applicationContext.getBean(WebSocketMessageRepository.class);


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        SocketSession session = SocketSession.getSession(ctx);
        TypeToken<HashMap<String, String>> typeToken = new TypeToken<HashMap<String, String>>() {
        };

        Gson gson=new Gson();
        java.util.Map<String,String> map = gson.fromJson(msg.text(), typeToken.getType());
        UserRespVo user = null;
        LocalDate now = LocalDate.now();
        switch (map.get("type")) {
            case "msg":
                WebSocketMessageResult result = new WebSocketMessageResult();
                user = session.getUser();
                result.setType("msg");
                result.setMsg(map.get("msg"));
                result.setUserOpenId(user.getUsername());
                result.setUserAvatarUrl(user.getHeadImageUrl());
                result.setUserNickName(user.getNickname());
                result.setChannelNum(session.getGroup());
                result.setSendDateTime(LocalDateTime.now());
                webSocketMessageRepository.save(result);
                SessionGroup.inst().sendToOthers(result, session);
                break;
            case "init":
                String room = map.get("room");
                session.setGroup(room);
                String openId = map.get("username");
                System.out.println("连接信息："+openId);
                user = iUserinfoService.getUserByUsername(openId);
                session.setUser(user);
                SessionGroup.inst().addSession(session);
                break;
            default:
                break;
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        // 是否握手成功，升级为 Websocket 协议
        if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {
            // 握手成功，移除 HttpRequestHandler，因此将不会接收到任何消息
            // 并把握手成功的 Channel 加入到 ChannelGroup 中
            new SocketSession(ctx.channel());
        } else if (evt instanceof IdleStateEvent) {
            IdleStateEvent stateEvent = (IdleStateEvent) evt;
            if (stateEvent.state() == IdleState.READER_IDLE) {
                System.out.println("握手成功...");
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}